#include "DirectoryEntry.h"
#include "FileOperations.h"
#include <string.h>

DirectoryEntry::DirectoryEntry()
{
	nFileSize = 0;
	LastWriteTime = 0;
}

DirectoryEntry::~DirectoryEntry()
{
	FileName.clear();
}


int DirectoryEntry::SortCompare(const DirectoryEntry* item1, const DirectoryEntry* item2)
{
	// Returns -1 if file1 < file2
	// Returns 0 if file1 == file2
	// Returns 1 if file1 > file2
	// This is just for sorting by the file size. If they're the same size, then it's sorted by last modified date.
	// Compare file name.	
	// Compare by size.
	INT64 compare = item1->nFileSize - item2->nFileSize;
	if (compare < 0)
	{
		return -1;
	}
	if (compare > 0)
	{
		return 1;
	}
	// Compare by last modified date.
	compare = item1->LastWriteTime - item2->LastWriteTime;
	if (compare < -60)
	{
		return -1;
	}
	if (compare > 60)
	{
		return 1;
	}
	// Compare file names.
	compare = CompareFileNames(&(item1->FileName), &(item2->FileName));
	return (int)compare;
}

int DirectoryEntry::CompareFileNames(const gstring *file1, const gstring *file2)
{
	size_t file1Length = file1->length();
	size_t file2Length = file2->length();
	size_t loop;
	size_t length = file1Length < file2Length ? file1Length : file2Length;
	gchar ch1;
	gchar ch2;
	if (FileOperations::AreFileNamesCaseSensitive())
	{
		if (length > 0)
		{
			loop = memcmp(file1->c_str(), file2->c_str(), static_cast<size_t>(length) * sizeof(gchar));
			if (loop != 0)
			{
				return (int)loop;
			}
		}
	}
	else
	{
		for (loop = 0; loop < length; loop++)
		{
			ch1 = toupper((*file1)[loop]);
			ch2 = toupper((*file2)[loop]);
			if (ch1 < ch2)
			{
				return -1;
			}
			if (ch1 > ch2)
			{
				return 1;
			}
		}
	}
	if (file1Length < file2Length)
	{
		return -1;
	}
	if (file1Length > file2Length)
	{
		return 1;
	}
	if (FileOperations::AreFileNamesCaseSensitive())
	{
		if (file1 < file2)
		{
			return -1;
		}
		if (file1 > file2)
		{
			return 1;
		}
	}
	else
	{
		size_t file1Length = file1->length();
		size_t file2Length = file2->length();
		size_t loop;
		size_t length = file1Length < file2Length ? file1Length : file2Length;
		gchar ch1;
		gchar ch2;
		for (loop = 0; loop < length; loop++)
		{
			ch1 = toupper((*file1)[loop]);
			ch2 = toupper((*file2)[loop]);
			if (ch1 < ch2)
			{
				return -1;
			}
			if (ch1 > ch2)
			{
				return 1;
			}
		}
		if (file1Length < file2Length)
		{
			return -1;
		}
		if (file1Length > file2Length)
		{
			return 1;
		}
	}	
	return 0;
}
